import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';

// services
import { ConstantService } from './constant.service';
import { StorageService } from './storage.service';

// plugins
import _ from 'lodash';
import md5 from 'js-md5';

// environment
import { url, port, client } from './environment.service';

@Injectable()
export class ServerService {
    /**
     * 请求方法
     * METHOD: POST
     * @param api 请求数据接口 
     * @param param 参数
     */
    fetch(api, data): Promise<any> {
        // 替换数据
        const param = _.defaultsDeep({}, this.constant.requestBody); // 此处需要深拷贝才能不影响使用
        // if (api !== 'login') {
        //     const token = this.storage.getItem(this.constant.storage.token);
        //     if (token) {
        //         param.body.token = token;
        //     } else {
        //         this.message.error('抱歉,您还未登录,请先登录');
        //         this.router.navigate(['/login']);
        //         return;
        //     }
        // }
        param.data = data;
        delete param.body.hmac;
        // 加密
        param.body.hmac = this.encrpt(param);
        return new Promise((resolve, reject) => {
            this.http.post(`${url}:${port}/${client}/${api}`, param)
                .subscribe((res: Response) => {
                    const result = res.json();
                    if (result.success) {
                        resolve(result);
                    } else {
                        this.message.error(result.message);
                        resolve(undefined);
                    }
                });
        });
    }

    // 加密算法
    encrpt(data: object): string {
        return md5(Object.values(data).map((v) => v = JSON.stringify(v)).concat([this.constant.md5Key]).join(''));
    }

    constructor(
        private http: Http,
        private constant: ConstantService,
        private storage: StorageService,
        private message: NzMessageService,
        private router: Router
    ) {}
}